package com.boruan.shengtangfeng.admin.jwt.exception;

import java.io.IOException;
import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.boruan.shengtangfeng.core.utils.GlobalReponse;
import com.boruan.shengtangfeng.core.utils.GlobalReponseResultEnum;

/**
 * jwt 未授权 异常处理
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

	private static final long serialVersionUID = -8970718410437077606L;

	private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationEntryPoint.class);

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		logger.info("拦截到登陆授权异常：" + authException.getMessage());
		logger.info(request.getRequestURI());
		GlobalReponseResultEnum authorizeResultEnum;
		GlobalReponse globalReponse;
		if (authException instanceof TokenException) {/** 无效的token **/
			authorizeResultEnum = GlobalReponseResultEnum.TOKEN_ERROR;
		} else if (authException instanceof UserVerificationException) {/** 用户验证未通过 **/
			authorizeResultEnum = GlobalReponseResultEnum.USER_LACK_PERMISSION;
		} else if (authException instanceof DriverVerificationException) {/** 司机端验证未通过 **/
			authorizeResultEnum = GlobalReponseResultEnum.DRIVER_LACK_PERMISSION;
		} else {
			authorizeResultEnum = GlobalReponseResultEnum.TOKEN_ERROR;
		}
		globalReponse = new GlobalReponse(authorizeResultEnum);
		response.getWriter().write(JSON.toJSONString(globalReponse));
	}
}
